<template>
	<view>
		<view class="gui-form-item gui-margin-top-large gui-padding">
			<view>
				<textarea v-model="remark" name="remark" value="" placeholder="给店家留言" 
				class="gui-textarea gui-bg-gray gui-border-box" style="width:690rpx;" />
			</view>
		</view>
		<view class="gui-margin-top gui-padding gui-flex gui-justify-content-end gui-align-items-center">
			<text class="gui-text-small gui-color-gray" style="margin-right: 10rpx;">是否配送</text>
			<switch  name="type" @change="switchChange" color="#F66867" style="zoom: 0.8;" value="1" :checked="isDistribution"/>
	
		</view>
		<block v-if="isDistribution">
			<view class="gui-card-view gui-border-b "  v-for="(item,index) in addressLists" :key="index" :data-index="index" @tap.stop="choose">
					<view class="gui-card-body gui-flex gui-rows gui-nowrap">
						<text class="gui-select-list-icon gui-icons gui-block-text gui-select-list-ring gui-select-list-icon-l"
						v-if="!item.checked">&#xe762;</text>
						<text class="gui-select-list-icon gui-icons gui-block-text gui-select-list-ring gui-select-list-icon-l gui-fade-in gui-select-list-current"
						v-if="item.checked">&#xe685;</text>
						<view class="gui-card-desc">
							<view class="gui-flex gui-rows gui-nowrap gui-align-items-center">
								<text class="gui-card-name">{{item.name}}</text>
								<text class="gui-text-small gui-color-blue">{{item.phone}}</text>
							</view>
							<text class="gui-card-text gui-block-text" style="margin-top:10rpx;">{{item.province}}-{{item.city}}-{{item.area}}-{{item.address}}</text> 
						</view>
					</view>
			</view>
		</block>
	
		<view class="gui-printList-footer gui-bg-gray  gui-border-box gui-border-t">
			<view class="gui-flex gui-rows gui-space-between gui-align-items-center">
				<view></view>
				<text class="gui-printList-checkout gui-bg-red gui-block-text gui-color-white" 
				@tap="goPrint">去打印</text>
			</view>
			<!-- 如果购物车处于switch页面，请删除下面的组件 -->
			<view>
				<gui-iphone-bottom></gui-iphone-bottom>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				remark:'',
				//是否配送
				isDistribution:false,
				//是否有地址
				hasAddress:false,
				addressLists : [],
				addressSelected:{}
			}
		},
		methods: {
			goPrint:function(){
				//1、检查用户余额是否足够
				if(uni.getStorageSync('printCount')>uni.getStorageSync('balance'))
				{
					uni.showModal({
						title:"提示",
						content:"你的余额不足",
						confirmText:"去充值",
						success: (res) => {
							if (res.confirm) {
								uni.switchTab({
									url:"/pages/rechargeItem/rechargeItem"
								})
							} else if (res.cancel) {
								uni.switchTab({
									url:"/pages/index/index"
								})
							}
						}
					})
					return;
				}
				//3、上传图片或者文件到七牛
				let fileList = uni.getStorageSync('printList');
				this.$http.qnFileUpload(
				{
				    files:fileList, // 必填 临时文件路径 格式: [{path: "图片地址"}]
				    load: true, //（默认 true 说明：本接口是否提示加载动画）
				    maxSize: 300000, //（默认 无 说明：上传的文件最大字节数限制，默认不限制）
				    onEachUpdate: res => {
				        //console.log("单张上传成功返回：",res);
				    },
				    Update: res => {
				        //console.log("上传进度返回：",res);
				    }
				}).then(res => {
				   console.log(res)
					let fileData =[];
					//设置订单状态 如果是纯图片的话把订单状态设为 待打印  1  并且减去当前的页数
					
					//如果 含有文件的话把订单设成 待处理 2  在处理完成后减去当前页数 
					//订单状态
					let status = 1
					let myflag = true
					let count = 0;
					for (let i=0;i<res.length;i++) {
						if(res[i].type == "file" && myflag){
							myflag = false
						
							status = 2
						}
						fileData[i] = {
							name:res[i].filename,
							count:res[i].count,
							url:res[i].url,
							type:res[i].type
						}
					}
				
					 console.log("全部上传完返回结果：",fileData);
					 //4、创建数据库订单
					 //整理入库数据 truck_type  order_remark file
					 
					 //是否配送
					  let truck_type = 0
					  //配送的话 需要 地址ID
					  let addressId =''
					  let phone=''
					 if(this.isDistribution){
						 truck_type = 1
						 addressId = this.addressSelected.id
						 phone = this.addressSelected.phone
					 }
					let newBalance;
					//如果 status == 1 说明 该订单为纯 图片文件 直接从用户余额当中减去当前用量	
					if(status == 1) {	
						//2,从余额中减去当前数量
						newBalance = uni.getStorageSync('balance')-uni.getStorageSync('printCount');
						count = uni.getStorageSync('printCount');
						uni.setStorageSync('balance',newBalance)
					}else{
						//如果含有文件后台统一将数量暂存为0，并将订单状态设为待处理
						count = 0 
					}
					 let finalData = {
						 truck_type,
						 address_id:addressId,
						 file:fileData,
						 order_remark:this.remark,
						 status,
						 newBalance,
						 count,
						 phone
					 }
				
					 this.$http.request({
						 url:"auth.Order/set",
						 method:"POST",
						 data:finalData,
						 withToken:true
					 }).then(res=>{
						 
						 //清除缓存中的 打印列表，清除缓存中的打印数量
						 uni.removeStorage({
						     key: 'printList',
						 	});
						uni.showModal({
							title:"提示",
							content:"订单已提交，请留意通知",
							confirmText:"查看订单",
							success: (res) => {
								if (res.confirm) {
									uni.switchTab({
										url:"/pages/my/order/order",
										success:(res)=>{
											
											let page = getCurrentPages().pop();
											console.log(page)
											if (page == undefined || page == null) return;
											page.reload;
										}
									})
								} else if (res.cancel) {
									uni.switchTab({
										url:"/pages/index/index"
									})
								}
							}
						})
					 }).catch(err=>{
						 console.log('创建订单失败')
					 })
				});
				
				
				
			},
			switchChange:function(){
				this.isDistribution = !this.isDistribution
				//2、如果需要配送，用户是否有默认地址
				if(this.isDistribution && !this.hasAddress){
					//如果缓存中有地址数据 直接赋值
					if(uni.getStorageSync('addressLists')){
						this.addressLists = uni.getStorageSync('addressLists')
						for(let i in this.addressLists){
							if(this.addressLists[i].checked){
								this.addressSelected = this.addressLists[i]
							}
						}
						return;
					}
					this.$http.request({
						url:'auth.Address/get',
						method:"GET",
						withToken:true
					}).then(res=>{
						if(res.list.length == 0 ){
							this.isDistribution=false
							uni.showModal({
								title:"提示",
								content:"请添加至少一个收货地址",
								confirmText:"添加地址",
								success: (res) => {
									if (res.confirm) {
										uni.navigateTo({
											url:"/pages/my/addressAdd/addressAdd"
										})
									} else if (res.cancel) {
									}
								}
							})
							return;
						}else{
							this.hasAddress = true;
							for(let i=0;i<res.list.length;i++){
								if(res.list[i].type == 1 ){
									this.addressSelected = res.list[i]
									res.list[i].checked = true;
								}else{
									//如果没有默认地址选择第一个
									if(i==0){
										res.list[i].checked = true;
									}else{
										res.list[i].checked = false;
									}
									
								}	
							}
							//将得到地址存入缓存 
							uni.setStorageSync('addressLists',res.list)
							this.addressLists = res.list
						}
					}).catch(
						err => {
						console.log(err)
						}
					)
				}else{
					this.addressSelected = {}
				}
			},
			choose:function(e){
				var index = e.currentTarget.dataset.index;
				for(let i=0;i<this.addressLists.length;i++){
					this.addressLists[i].checked = false;
				}
				this.addressLists[index].checked = true;
				this.addressSelected = this.addressLists[index]
				
			}
		}
	}
</script>

<style>
	.gui-printList-footer{position:fixed; z-index:99; left:0; bottom:0; width:750rpx; padding-left:30rpx;}
	.gui-printList-checkbtn{width:200rpx;}
	.gui-printList-count{width:200rpx; flex:1;}
	.gui-printList-checkout{width:260rpx; height:100rpx; line-height:100rpx; font-size:28rpx; text-align:center;}
	/* 卡片视图 */
	.gui-card-view{background-color:#FFFFFF; padding:25rpx;}
	.gui-card-body{}
	.gui-card-img{width:100rpx; height:100rpx; border-radius:80rpx;}
	.gui-card-desc{width:400rpx; margin-left:25rpx; flex:1;}
	.gui-card-name{font-size:28rpx; color:#333333; line-height:40rpx; margin-right:20rpx;}
	.gui-card-text{line-height:40rpx; font-size:24rpx; color:#888888;}
	.gui-card-footer{ margin-top:25rpx;}
	.gui-card-footer-item{width:100rpx; text-align:center; flex:1; line-height:38rpx; font-size:26rpx; color:#666666;}
</style>
